#include <iostream>
#include <string>
#include <vector>
#include <pthread.h>
#include <unistd.h>
using namespace std;

pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;

void *Acode(void *args)
{
    while (true)
    {
        pthread_mutex_lock(&gmutex);
        sleep(1);
        cout << "i am process A" << endl;
        pthread_cond_signal(&gcond);
        pthread_cond_wait(&gcond, &gmutex);
        pthread_mutex_unlock(&gmutex);
    }
}
void *Bcode(void *args)
{
    while (true)
    {
        pthread_mutex_lock(&gmutex);
        sleep(1);
        cout << "i am process B" << endl;

        pthread_cond_signal(&gcond);
        pthread_cond_wait(&gcond, &gmutex);
        pthread_mutex_unlock(&gmutex);
    }
}
void startA(vector<pthread_t> &tidptr)
{
    pthread_t tidA;
    int n = pthread_create(&tidA, nullptr, Acode, nullptr);
    if (n == 0)
    {
        cout << "create A success" << endl;
    }
    tidptr.push_back(tidA);
}

void startB(vector<pthread_t> &tidptr)
{
    pthread_t tidB;
    int n = pthread_create(&tidB, nullptr, Bcode, nullptr);
    if (n == 0)
    {
        cout << "create A success" << endl;
    }
    tidptr.push_back(tidB);
}

void waitThread(vector<pthread_t> &tids)
{
    for (auto tid : tids)
    {
        pthread_join(tid, nullptr);
    }
}
int main()
{
    vector<pthread_t> tids;
    startA(tids);
    startB(tids);
    waitThread(tids);

    return 0;
}